import React, { Component, useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import PersonInfo from './components/personInfo';
import { Button, Table, Divider, Dropdown, Menu, message, Form, Input, Select, Switch, Modal, Alert, Descriptions, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { addRule } from './service';
import { connect } from 'umi';
import axios from 'axios'
import moment from 'moment'

const { Option } = Select
const { Search } = Input;

/**
 * 添加节点
 * @param fields
 */





const BasicForm = (props) => {
    const {
        loading,
        dispatch,
        profileAndbasic: { list },
    } = props;
    const [resetpassvisible, setpassvisible] = useState(false);//重置密码弹框
    const [createModalVisible, handleModalVisible] = useState(false);//新建用户弹框
    const [currentclass, setcurrentclass] = useState(null);//班级成绩
    const [current, setCurrent] = useState(null);
    const [gradeVisible, setgradeVisible] = useState(false);//成绩查询弹框
    const [personVisible, setpersonVisible] = useState(false);//个人信息弹框
    const [updateModalVisible, handleUpdateModalVisible] = useState(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);//选择列表
    const [data, setdata] = useState([]);//列表数据
    const [detail, setdetail] = useState({});//修改个人数据

    let query = useRef({
        pageIndex: 1,
        pageSize: 20,
        name: "",
        order:"id desc"

    })
    useEffect(() => {
        dispatch({
            type: 'profileAndbasic/fetch',
            payload: {
                ...query.current
            },
        });
    }, []);
    const paginationProps = {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSize: query.current.pageSize,
        total: list.total,
        onChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            console.log(query.current)

            dispatch({
                type: 'formAndbasicForm/fetch',
                payload: {
                    ...query.current
                },
            });
            //   console.log(page,currents,pageSize,pagination)            
        },

        onShowSizeChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            dispatch({
                type: 'formAndbasicForm/fetch',
                payload: {
                    ...query.current
                },
            });
        }
    };
    const [form] = Form.useForm();
    const onFinish = async (values) => {
        const fieldsValue = await form.validateFields();
        console.log(fieldsValue)
        query.current = { ...query.current, ...fieldsValue }
        dispatch({
            type: 'formAndbasicForm/fetch',
            payload: {
                ...query.current
            },
        });
    };
    const handleCancel = values=>{
        handleModalVisible(false)
    }
    const  handleAdd = values => {
        console.log(values,current)
        const id = current ? current.id : undefined;
       let res= dispatch({
            type: 'profileAndbasic/submit',
            payload: {
                id,
                ...values,
            },
        });
      
        // dispatch({
        //     type: 'profileAndbasic/fetch',
        //     payload: {
        //         ...query.current
        //     },
        //   });
    
    };
    const columns = [
        {
            title: '考试名称',
            dataIndex: 'exam_name',

        },

        {
            title: '实验名称',
            dataIndex: 'experiment_name',
        },
        {
            title: '老师',
            dataIndex: 'teacher_name',
        },
        {
            title: '开始时间',
            dataIndex: 'start_time',
        },
        {
            title: '结束时间',
            dataIndex: 'end_time',
        },
        {
            title: '时长',
            dataIndex: 'exam_time',
        },
        {
            title: '状态',
            dataIndex: 'name',
            render:(val,record)=>{
                var str = ''
                var sta=''
                var a = moment(record.end_time).isBefore(new Date())
                var b = moment(record.start_time).isAfter(new Date());
                var c = moment(new Date()).isBetween(record.start_time, record.end_time );
                if (a) {
                    str='已结束'
                    sta=1
                }else if (b) {
                    str='未开始'
                    sta=2

                }else{
                    str='进行中'
                    sta=3

                }
                record['staus']=sta
                // console.log(record)
                 return str
            }
        },
        {
            title: '参与成员',
            dataIndex: 'examCount',
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a onClick={() => {setgradeVisible(true);setcurrentclass(record)}}>查看成绩</a>
                    <Divider type="vertical" />
                    {/* 和新建界面一样，用同一个组件，这不过这个根据ID打开那边要获取值 */}
                    <a onClick={() => { handleModalVisible(true); setCurrent(record) }}>修改考试</a>
                    <Divider type="vertical" />

                    <Divider type="vertical" />
                    <a href="#" onClick={()=>{del(record)}}>删除</a>

                </>
            ),
        },
    ];
    // 修改个人信息
    const changeinfo = (record) => {
        // 获取个人信息传到子组件

        console.log(record)
    };
     // 删除
     const deleteItem = id => {
        dispatch({
          type: 'profileAndbasic/submit',
          payload: {
            id,
          },
        });   
      };
    const del = (currentItem) => {
        // 检测删除状态
        let str=''
        if (currentItem) {
            str=currentItem.id
            var a = moment(currentItem.end_time).isBefore(new Date())//已结束
            var b = moment(currentItem.start_time).isAfter(new Date());//未开始
            var c = moment(new Date()).isBetween(currentItem.start_time, currentItem.end_time );
            if (a) {
                message.error('考试已结束，无法删除')
                return;
            }else if (c) {
              message.error('考试进行中，无法删除')
              return;
            }
        }else{
          //字符串拼接
          var arr=[]
          if (selectedRowKeys.length==0) {
            message.error('当前没有选中选项')
            return;
           }else{
            selectedRowKeys.map(item=>{
               var a=list.list.find(item1=>{
                   return item1.id==item
               })
               if (a.staus==2) {
                arr.push(item)
               }
               console.log(a)
            })   
            str=arr.join(',')
         }
        }
        console.log(currentItem,str)
        let content = currentItem? `\n确定要取消 ${currentItem.exam_name }考试吗？` : `本次选中 ${selectedRowKeys.length} 个考试，\n已开始或结束的考试不能删除，同时只删除未开始的考试，确定删除吗`
        Modal.confirm({
            title: '删除任务',
            content: content,
            okText: '确认',
            cancelText: '取消',
            onOk: () => deleteItem(str),
          });
    }
        //  导出
        const exportExcel = () => {
            let config = {
                headers: {
                    'Authorization': `${sessionStorage.getItem('tokenHead')} ${sessionStorage.getItem('token')}`,
                },
                responseType:'blob'
            }
            console.log(selectedRowKeys)
            if (selectedRowKeys.length==0) {
                message.error('当前没有选中数据')
                return
    
            }
            selectedRowKeys.map(id=>{
                axios.get(`/exam/exportExcel?examId=${id}`, config)
                .then(res => {
                    console.log(res)
                    if (res) {
                        let blob = new Blob([res.data], {type: res.data.type}      
                        )
                        var link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        var itemname= list.list.find(item=>{
                            return  item.id==id
                         })
                         console.log(itemname)
                        link.download = itemname.exam_name+'考试表';              
                        link.click();
                  
                      }else{
                        message.error(res.message)
                      }
                })
                .catch(error => {
                    message.error(`file upload failed.`);
                });
            })
           
    
        };
     


    // 提示
    const onClose = (e) => {
        console.log(e, 'I was closed.');
    };

    //筛选数据
    const onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        setSelectedRowKeys(selectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    const layout = {
        labelCol: {
            span: 10,
        },
        wrapperCol: {
            span: 10,
        },
    };
    const formRef = React.createRef();
    return (
        <PageHeaderWrapper>
            <div >

                {/* <Modal
                    title="个人信息"
                    visible={personVisible}
                    onOk={() => hidepersonModal(false)}
                    onCancel={() => hidepersonModal(false)}
                    okText="确认"
                    cancelText="取消"
                >
                    <Descriptions title="若信息有误请联系管理员" size='small'>
                        <Descriptions.Item label="账号">Cloud Database</Descriptions.Item>
                        <Descriptions.Item label="姓名" span={2}>Prepaid</Descriptions.Item>
                        <Descriptions.Item label="类型" >18:00:00</Descriptions.Item>
                        <Descriptions.Item label="工号">$80.00</Descriptions.Item>

                    </Descriptions>
                </Modal> */}

                  <PersonInfo
                    currentclass={currentclass}
                    onCancel={() => setgradeVisible(false)}
                    modalVisible={gradeVisible}
                />
                <Form layout='inline'>
                    <Form.Item label="">
                        <Button type="primary" onClick={() => {handleModalVisible(true);setCurrent(null)}}>新建</Button>
                        {/* 增加 */}
                        {/* createform子组件 通过属性的方式传递本地父组件的增加方法和本地值 */}
                        <CreateForm
                            onSubmit={handleAdd}
                            onCancel={handleCancel}
                            current={current}
                            modalVisible={createModalVisible}
                        />
                    </Form.Item>

                    <Form.Item label="">
                        <Button type="primary" onClick={()=>{del()}}>删除</Button>
                    </Form.Item>
                    <Form.Item label="">
                    <Button type="primary" onClick={() => { exportExcel() }}>
                            <UploadOutlined /> 导出
                           </Button>
                    </Form.Item>
                </Form>
            </div>
            <div style={{ marginTop: "50px", marginBottom: "20px" }}>
                <Form {...layout} layout='inline' form={form} name="control-ref" >
                    <Form.Item
                        style={{ width: '200px' }}
                        name="name"
                        label="关键字"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >

                        <Search
                            placeholder="考试名称，老师名称"
                            onSearch={onFinish}
                            style={{ width: 300 }}
                        />
                    </Form.Item>
                </Form>
            </div>
            <Alert
                message='已经开始的考试，和结束的考试，都不能再做修改和删除'
                type="warning"
                closable
                onClose={onClose}
            />
            <Table rowSelection={rowSelection} columns={columns} pagination={paginationProps} dataSource={list.list} rowKey={record => record.id} />
        </PageHeaderWrapper>
    )

}
export default connect(({ profileAndbasic, loading }) => ({
    profileAndbasic,
    loading: loading.models.profileAndbasic,
}))(BasicForm);